﻿Ext.define('app.system.user.Edit',
{
    extend: 'Ext.window.Window',
    autoScroll: true,
    modal: true,
    width: 600,
    height: 400,
    layout: 'border',
    userId: 0,
    bodyStyle: 'padding:1px',
    initComponent: function () {
        var me = this;
        me.items = [me.getForm(), me.getQuanTree()];
        me.buttons = [
            { text: '保存', scope: this, handler: me.onSubmit },
            { text: '关闭', handler: function () { me.close(); } }
        ]
        me.callParent();
    },
    listeners: {
        afterrender: function (me) {
            App.AjaxPost('/api/services/app/user/GetUserForEdit', { Id: me.userId }, function (data) {
                var cbo_tree = me.getComboTree();
                var cboValue = "";
                if (data.result.user.businessId > 0) {
                    cboValue = data.result.businessName;
                }
                if (data.result.user.rdCenterId > 0) {
                    cboValue = data.result.rdCenterName;
                }
                if (data.result.user.laboratoryId > 0) {
                    cboValue = data.result.laboratoryName;
                }
                cbo_tree.setRawValue(cboValue);
                cbo_tree.BusinessId = data.result.user.businessId;
                cbo_tree.RdCenterId = data.result.user.rdCenterId;
                cbo_tree.LaboratoryId = data.result.user.laboratoryId;

                var roles = [];
                for (var i = 0; i < data.result.roles.length; i++) {
                    var role = data.result.roles[i];
                    if (role.isAssigned) {
                        roles.push(role.roleId);
                    }
                }
                me.form.query("tagfield[name=roles]")[0].setValue(roles);
                me.getForm().getForm().setValues(data.result.user);
            });
        }
    },
    getComboTree: function () {
        if (!this.comboTree) {
            this.comboTree = Ext.create("app.ux.ComboTreeBox", {
                // id: 'cbo_tree',
                fieldLabel: '所属科室',
                editable: false,
                store: new Ext.data.TreeStore({
                    root: {
                        expanded: true
                    },
                    autoLoad: true,
                    nodeParam: 'parentId',
                    // 根节点的参数值是0
                    defaultRootId: "0",
                    proxy: {
                        type: 'ajax',
                        reader: {
                            type: 'json',
                            rootProperty: function (node) {
                                return node.result || node.children;
                            }
                        },
                        url: '/api/services/app/laboratory/GetTree'
                    }
                })
            });
        }
        return this.comboTree;
    },
    getForm: function () {
        var me = this;
        if (!this.form) {
            this.form = new Ext.form.Panel({
                title: '用户信息',
                defaultType: 'textfield',
                border: false,
                region: 'west',
                width: 300,
                defaults: { anchor: '100%' },
                fieldDefaults: {
                    labelWidth: 90,
                    labelAlign: "right",
                    flex: 1,
                    margin: 6
                },
                items: [
                    { xtype: 'hidden', name: 'id' },
                    //{ xtype: 'hidden', name: 'password' },
                    {
                        fieldLabel: '用户名',
                        allowBlank: false,
                        name: 'userName'
                    },
                    {
                        fieldLabel: '名称',
                        allowBlank: false,
                        name: 'name'
                    },
                    {
                        fieldLabel: '邮箱地址',
                        allowBlank: false,
                        name: 'emailAddress'
                    },
                    me.getComboTree(),
                    {
                        xtype: 'tagfield',
                        //id: 'txt_role',
                        fieldLabel: '系统角色',
                        name: 'roles',
                        store: Ext.create("app.ux.PrmStore", { url: '/api/services/app/role/GetAll' }),
                        valueField: 'id',
                        displayField: 'displayName'
                    },
                    {
                        xtype: 'checkbox',
                        //id: 'chk_active',
                        fieldLabel: '是否可用',
                        name: 'isActive',
                        inputValue: true
                    }
                ]
            });
        }
        return this.form;
    },
    getQuanTree: function () {
        var me = this;
        if (!this.tree) {
            this.tree = new Ext.tree.Panel({
                title: '选择区域',
                border: true,
                region: 'center',
                scrollable:true,
                useArrows: true,
                rootVisible: false,
                store: new Ext.data.TreeStore({
                    root: { expanded: true },
                    autoLoad: true,
                    nodeParam: 'parentId',
                    // 根节点的参数值是0
                    defaultRootId: "0",
                    proxy: {
                        type: 'ajax',
                        reader: {
                            type: 'json',
                            rootProperty: function (node) {
                                return node.result || node.children;
                            }
                        },
                        url: '/api/services/app/quan/GetUserQuan?userId=' + me.userId
                    }
                }),
                root: { id: '0', text: '' },
                listeners: {
                    afterrender: function (tree) { tree.expandAll(); },
                    checkchange: function (node, checked, eOpts) {
                        if (checked) {
                            node.eachChild(function (child) {
                                me.checkChild(child, false);
                            });
                        } else {
                            node.eachChild(function (child) {
                                me.checkChild(child, false);
                            });
                        }
                        me.checkParent(node);// 进行父级选中操作
                    }
                }
            });
        }
        return this.tree;
    },
    checkChild: function (node, check) {
        var me = this;
        node.set('checked', check);
        if (node.isNode) {
            node.eachChild(function (child) {
                me.checkChild(child, check);
            });
        }
    },
    nodep: function (node) {
        var bnode = true;
        Ext.Array.each(node.childNodes, function (v) {
            if (!v.data.checked) {
                bnode = false;
                return;
            }
        });
        return bnode;
    },
    checkParent: function (node) {
        var me = this;
        if (node.parentNode != null) {
            if (me.nodep(node.parentNode)) {
                node.parentNode.set('checked', false);
            } else {
                node.parentNode.set('checked', false);
            }
            me.checkParent(node.parentNode);
        }
    },
    onSubmit: function () {
        var me = this;
        var cboTree = me.getComboTree();
        var json = me.getForm().getForm().getValues();
        var user = {
            Id: me.userId,
            Name: json.name,
            IsActive: json.isActive,
            EmailAddress: json.emailAddress,
            Surname: json.name,
            UserName: json.userName,
            // Password: json.password,
            //PasswordRepeat: json.password,
            BusinessId: cboTree.BusinessId,
            RdCenterId: cboTree.RdCenterId,
            LaboratoryId: cboTree.LaboratoryId
        };
        var role = me.form.query("tagfield[name=roles]")[0];
        var assignedRoleNames = role.getRawValue();
        var roles = [];
        if (assignedRoleNames != "") {
            roles = assignedRoleNames.split(",")
        }

        var quans = [];
        var quanCheckeds = me.getQuanTree().getChecked();
        for (var i = 0; i < quanCheckeds.length; i++) {
            var node = quanCheckeds[i];
            if (parseInt(node.data.id) > 0) {
                quans.push({ key: node.data.id, value: node.data.parentId });
            }
        }
        App.AjaxPost('/api/services/app/user/CreateOrUpdateUser', { user: user, assignedRoleNames: roles, quans: quans }, function () {
            me.fireEvent("savesuccess");
        });
    }
});